package com.health.work.activity;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.health.work.R;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UploadUtil;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;


/**
*
* 项目名称：HealthNet
* 类名称：注册详细 档案人员
* 类描述：
* 创建人：Zhai
* 创建时间：2012-11-8 下午2:26:27
* 修改人：Zhai
* 修改时间：2012-11-8 下午2:26:27
* 修改备注：
* @version
*
*/
public class RegisteInfoActivity extends Activity implements OnClickListener {
	
	protected static final int SUCCESS = 0;
	protected static final int ERROR = 1;
	protected static final int ERROR_ID = 2;
	
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	protected static final int SUCCESS_PHOTO = 10;

	protected static final int ERROR_PHOTO = 11;

	private File mCurrentPhotoFile;// 照相机拍照得到的图片
	
	private ImageView camera;
	
	protected String str_img;
	
	private Bitmap photo;
	

	private EditText user_id;
	private EditText user_name;
	private EditText user_phone;
	private TextView back;
	private Button invalidate;
	
	private Button btnback;
	private Thread thread;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				TipsUtil.showAlertFinish(RegisteInfoActivity.this, null,
						"注册成为档案会员成功。");
				break;
			case ERROR:
				TipsUtil.showAlert(RegisteInfoActivity.this, null,
						"注册成为档案会员失败。");
				break;
			case ERROR_ID:
				TipsUtil.showAlert(RegisteInfoActivity.this, null,
						"身份证号已被注册。");
				break;
			case SUCCESS_PHOTO:
				TipsUtil.showAlert(RegisteInfoActivity.this, null,
						"恭喜您，上传图片成功！");
				if(photo!=null){
					camera.setImageBitmap(photo);
				}
				break;
			case ERROR_PHOTO:
				TipsUtil.showAlert(RegisteInfoActivity.this, null,
						"上传图片失败！");
				break;
			default:
				break;
			}

		}

	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registerfilemember);
		init();
	}

	private void init() {
		user_id=(EditText)this.findViewById(R.id.txt_IDNum);
		user_name=(EditText)this.findViewById(R.id.txt_Name);
		user_phone=(EditText)this.findViewById(R.id.txt_PhoneNumer);
		user_phone.setText(UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.MOBILEPHONE));
		invalidate=(Button)this.findViewById(R.id.btnVerification);
		back=(TextView)this.findViewById(R.id.back);
		btnback=(Button)this.findViewById(R.id.btnback);
		
		camera=(ImageView)findViewById(R.id.camera);
		camera.setOnClickListener(this);
		
		back.setOnClickListener(this);
		invalidate.setOnClickListener(this);
		
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.btnVerification:
			if(inputCheck()){
				vertify();
			}
			break;
		case R.id.btnback:
			finish();
			break;
		case R.id.camera:
			doPickPhotoAction();
			break;
		default:
			break;
		}
	}
	
	private void vertify(){
		new Thread(new Runnable() {
				@Override
				public void run() {
					new RequestParamtersUtil().RegistrationWithIDNumber(user_id.getText().toString(),
							user_name.getText().toString(),user_phone.getText().toString(), str_img,new DefaultJSONData() {
	
								@Override
								public void parse(JSONObject object)
										throws JSONException {
									Log.e("RegistrationWithIDNumber", object.toString());
									
								}
	
								@Override
								public void parse(JSONArray array)
										throws JSONException {
								}
	
								@Override
								public void parse(String result)
										throws JSONException {
									Log.e("RegistrationWithIDNumber", result);
									if("0".equals(result)){
										handler.sendEmptyMessage(SUCCESS);
									}else if("1".equals(result)){
										handler.sendEmptyMessage(ERROR);
									}else if("2".equals(result)){
										handler.sendEmptyMessage(ERROR_ID);
									}
								}
							});
				}
			}).start();
	}

	private boolean inputCheck() {
		boolean flag=false;
		if (user_id.getText() == null
				|| user_id.getText().toString().length() !=18) {
			Toast.makeText(this, "身份证输入有误", Toast.LENGTH_SHORT).show();
		} else if (user_name.getText() == null
				|| user_name.getText().toString().length() ==0) {
			Toast.makeText(this, "姓名输入有误", Toast.LENGTH_SHORT).show();
		} else if(str_img == null){
			Toast.makeText(this, "照片不能为空", Toast.LENGTH_SHORT).show();
		} else{
			flag=true;
		}
		return flag;
	}
	
	
	/**
	 * 
	 */
	/**
	 * 
	 * 88888888888888888888888888888888888888888888888888888888888888888888888888
	 */

	// 以下代码是调用摄像头或者系统相册
	public void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices;
		choices = new String[2];
		choices[0] = "拍照"; // 拍照
		choices[1] = "从相册中选择"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("选择方式");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0: {
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							} else {
								Toast.makeText(
										RegisteInfoActivity.this,
										"出现异常", Toast.LENGTH_LONG).show();
							}
							break;

						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("CaseStorageActivity", "1:" + requestCode + "  2:"
				+ resultCode);
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
			case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
				photo = data.getParcelableExtra("data");
				System.out.println(photo);
				camera.setImageBitmap(photo);
//				String imageStr = BitmapBase64.getBitmapStringBase64(photo);
				upFile(1,null,photo);
				break;
			}
			case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			// doCropPhoto(mCurrentPhotoFile);
				photo = BitmapFactory.decodeFile(mCurrentPhotoFile.getPath());
//				photo=mCurrentPhotoFile;
				upFile(2,mCurrentPhotoFile,null);
				break;
			}
		}
	}
	
	protected void upFile(final int kind,final File file,final Bitmap bitmap) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {
			 private ProgressDialog dialog2 = null;
			 private String url="";
			@Override
			protected void onPreExecute() {
				if (dialog2 != null) {
				} else {
					dialog2 = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog2.setCancelable(true);
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if(kind==2){
					url=UploadUtil.uploadFile(file, HEALTHPASSPORT.URL_PIC,
						"file");
				}else{
					url=UploadUtil.uploadFile(bitmap,
							HEALTHPASSPORT.URL_PIC, "file");	
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
					dialog2.dismiss();
					dialog2 = null;
					if(url!=null&&url.length()>0){
						handler.sendEmptyMessage(SUCCESS_PHOTO);
						str_img=str_img+url+";";
						Log.e("img str", str_img);
					}else {
					}
			}
		};
		asyncLoad.execute(null);
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			mCurrentPhotoFile = new File(PHOTO_DIR, "health.jpg");// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 *  调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}
}
